package com.jeesite.modules.fl.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.fl.entity.Clinic;
import com.jeesite.modules.fl.entity.Enterprise;
import com.jeesite.modules.fl.service.ClinicService;
import com.jeesite.modules.fl.service.EnterpriseService;
import com.jeesite.modules.sys.entity.Area;
import com.jeesite.modules.sys.entity.DictData;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.utils.AreaUtils;
import com.jeesite.modules.sys.utils.UserUtils;


@Controller
@RequestMapping(value = "${adminPath}/fl/clinic")
public class ClinicController extends BaseController{
	
	@Autowired
	private ClinicService clinicService;
	@Autowired
	private EnterpriseService enterpriseService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Clinic get(String id, boolean isNewRecord) {
		return clinicService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequiresPermissions("fl:clinic:view")
	@RequestMapping(value = {"list", ""})
	public String list(Clinic clinic, HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("clinic", clinic);
		Enterprise entity = new Enterprise();
        entity.setStatus("0");
        List<Enterprise> enterpriseList = enterpriseService.findList(entity);
		List<DictData> dicts = new ArrayList<DictData>();
        for(Enterprise e:enterpriseList){
        	DictData data = new DictData();
        	data.setDictLabelOrig(e.getName());
        	data.setDictValue(e.getId());
        	dicts.add(data);
        }
        model.addAttribute("enterpriseDicts", dicts);
        model.addAttribute("enterpriseList", enterpriseList);
        List mapList = ListUtils.newArrayList();
		List cityList = ListUtils.newArrayList();
        List list = AreaUtils.getAreaAllList();
        for(int i = 0; i < list.size(); i++)
        {
            Area e = (Area)list.get(i);
            if("0".equals(e.getStatus()) && e.getAreaType().equals("1"))
            {
                mapList.add(e);
            }else if("0".equals(e.getStatus()) && e.getAreaType().equals("2"))
            {
            	cityList.add(e);
            }
        }
        model.addAttribute("mapList", mapList);
        model.addAttribute("cityList", cityList);
		return "modules/fl/clinicList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("fl:clinic:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Clinic> listData(Clinic clinic, HttpServletRequest request, HttpServletResponse response) {
		User user = UserUtils.getUser();
		if(!user.isAdmin()){
			clinic.getSqlMap().put("dsf", " and (EXISTS (SELECT 1 FROM fl_clinic_user WHERE users like '%"+user.getId()+"%' AND clinic=a.id) or EXISTS (SELECT 1 FROM js_sys_user WHERE user_code='"+user.getId()+"' AND user_code=a.create_by))");
		}
		Page<Clinic> page = clinicService.findPage(new Page<Clinic>(request, response), clinic);
		return page;
	}
	
	/**
	 * 查看编辑表单
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequiresPermissions("fl:clinic:view")
	@RequestMapping(value = "form")
	public String form(Clinic clinic, Model model) {
		model.addAttribute("clinic", clinic);
		List mapList = ListUtils.newArrayList();
		List cityList = ListUtils.newArrayList();
        List list = AreaUtils.getAreaAllList();
        for(int i = 0; i < list.size(); i++)
        {
            Area e = (Area)list.get(i);
            if("0".equals(e.getStatus()) && e.getAreaType().equals("1"))
            {
                mapList.add(e);
            }else if("0".equals(e.getStatus()) && e.getAreaType().equals("2"))
            {
            	cityList.add(e);
            }
        }
        model.addAttribute("mapList", mapList);
        model.addAttribute("cityList", cityList);
        Enterprise entity = new Enterprise();
        entity.setStatus("0");
        List<Enterprise> enterpriseList = enterpriseService.findList(entity);
        model.addAttribute("enterpriseList", enterpriseList);
		return "modules/fl/clinicForm";
	}
	
	/**
	 * 验证名称是否有效
	 * @param oldClinicName
	 * @param name
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("fl:clinic:edit")
	@RequestMapping(value = "checkClinicName")
	public String checkClinicName(String oldClinicName, String name) {
		if (name !=null && name.equals(oldClinicName)) {
			return "true";
		} else if (name !=null && clinicService.getByName(name) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("fl:clinic:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Clinic clinic) {
		clinicService.save(clinic);
		return renderResult(Global.TRUE, text("保存数据成功！"));
	}
	
	/**
	 * 停用数据
	 */
	@RequiresPermissions("fl:clinic:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(Clinic clinic) {
		clinic.setStatus(Clinic.STATUS_DISABLE);
		clinicService.updateStatus(clinic);
		return renderResult(Global.TRUE, text("停用数据成功"));
	}
	
	/**
	 * 启用数据
	 */
	@RequiresPermissions("fl:clinic:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(Clinic clinic) {
		clinic.setStatus(Clinic.STATUS_NORMAL);
		clinicService.updateStatus(clinic);
		return renderResult(Global.TRUE, text("启用数据成功"));
	}

	/**
	 * 不可预约
	 */
	@RequiresPermissions("fl:clinic:edit")
	@RequestMapping(value = "denySchedule")
	@ResponseBody
	public String denySchedule(Clinic clinic) {
		clinic.setAllowSchedule("0");
		clinicService.save(clinic);
		return renderResult(Global.TRUE, text("禁止预约更新成功"));
	}

	/**
	 * 可预约
	 */
	@RequiresPermissions("fl:clinic:edit")
	@RequestMapping(value = "allowSchedule")
	@ResponseBody
	public String allowSchedule(Clinic clinic) {
		clinic.setAllowSchedule("1");
		clinicService.save(clinic);
		return renderResult(Global.TRUE, text("允许预约更新成功"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("fl:clinic:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Clinic clinic) {
		clinicService.delete(clinic);
		return renderResult(Global.TRUE, text("删除数据成功！"));
	}
	
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		ExcelExport ee = new ExcelExport("诊所数据", Clinic.class);
		try {
			String fileName = "诊所数据导入模板.xlsx";
			List<Clinic> list = new ArrayList<Clinic>();
			list.add(new Clinic());
			ee.setDataList(list).write(response, fileName);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		} finally{
			ee.close();
		}
	}
	
	@RequestMapping(value = "export", method=RequestMethod.POST)
    public void exportFile(Clinic clinic, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		ExcelExport ee = new ExcelExport("诊所数据", Clinic.class);
		try {
            String fileName = "诊所数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; 	
            List<Clinic> list = clinicService.findList(clinic);
    		ee.setDataList(list).write(response, fileName);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出诊所失败！失败信息："+e.getMessage());
		} finally{
			ee.close();
		}
    }
    
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importData(MultipartFile file, String updateSupport)
    {
        String message;
        boolean isUpdateSupport = "1".equals(updateSupport);
        try{
	        message = clinicService.importData(file, Boolean.valueOf(isUpdateSupport));
	        return renderResult("true", (new StringBuilder()).append("posfull:").append(message).toString());
        }catch(Exception ex){
        	return renderResult("false", (new StringBuilder()).append("posfull:").append(ex.getMessage()).toString());
        }
    }

}
